package com.samp.lucene.spell;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.search.suggest.FileDictionary;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class BaseDemo {

	
	public static void main(String[] args) {
		try {
			String dictPath = "com/samp/lucene/spell/spell_data_01.txt";
			Directory spellIndexDirectory = FSDirectory.open(Paths.get("src/main/java/com/samp/lucene/spell/spellDir"));
			SpellChecker spellchecker = new SpellChecker(spellIndexDirectory );
			Analyzer analyzer = new IKAnalyzer(true, true, false);
			IndexWriterConfig config = new IndexWriterConfig(analyzer);
			config.setOpenMode(OpenMode.CREATE_OR_APPEND);
			spellchecker.setAccuracy(0.6f);
			InputStream is = BaseDemo.class.getResourceAsStream(dictPath); //取不到
			is = BaseDemo.class.getClassLoader().getResourceAsStream(dictPath);//可以取
			is = Files.newInputStream(Paths.get("src/main/java/"+dictPath));//ok,相对路径是相对于整个工程而言。
			if( is == null ){
				System.out.println("InputStream is null");
			}else{
				spellchecker.indexDictionary(new FileDictionary(is),config,false);
				String[] similars = spellchecker.suggestSimilar("中国凭安", 10);
				for (String similar : similars) {
					System.out.println(similar);
				}
			}
			spellIndexDirectory.close();
			spellchecker.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
